<?php
namespace app\index\controller;
use app\index\controller\BaseController;
use app\common\model\User;
use app\common\model\Banner;
use app\common\model\SmsLog;
class RegisterController extends BaseController{
  public function _initialize(){
    parent::_initialize();
    $this->Model = new User();
    $this->user_type = "member";
  }

  public function index(){
    $this->redirect(url("create"));
  }

  public function create(){
    if($this->request->isPost()){
      $data = $this->getPostData();

      $code = $this->request->post("code");
      $LogModel = new SmsLog();
      $code_res = $LogModel->validSendCode("register", $data["mobile"], $code);
      if($code_res["status"] == false){
        $this->error($code_res["msg"]);
      }
      $res = $this->Model->addUser($data);
      if($res["id"]){
        $this->success($res["msg"], 'login/login');
      }else{
        $this->error($res["msg"]);
      }
    }else{
      $BannerModel = new Banner();
      $banner = $BannerModel->randFindByType("login");
      $this->assign("banner", $banner);

      $this->action_seo("注册");

      return $this->fetch();
    }
  }

  public function ajax_check_unique(){
    if($this->Model->isFieldValueUnique()){
      echo("true");
    }else{
      echo("false");
    }
  }

  public function sms_code(){
    if($this->request->isPost()){
      $LogModel = new SmsLog();
      $mobile = $this->request->param("mobile");
      $res = $LogModel->sendRegistMsg($mobile);
    }else{
      $res = ["status" => false, "msg" => "请求方式不正确"];
    }
    return json($res);
  }

  private function getPostData(){
    $atl_name = $this->request->action();
    $data = ["user_type" => $this->user_type];
    $param_name = ["email", "nickname", "gender", "mobile", "url", "birthday", "password", "confirm_password"];
    $param = $this->request->post();
    foreach ($param_name as $key) {
      if(isset($param[$key])){
        $val = $param[$key];
      }else{
        $val = "";
      }

      switch ($key) {
      case "birthday":
        if(empty($val)){
          $val = NULL;
        }
        break;
      default:
        $val = trim($val);  
      }
      $data[$key] = $val;
    }
    return $data;
  }
}